<template>
	<view class="" style="width: 100vw;height: 100vh">
		<!-- <view  style="min-height: 100vh">
		<image src="/static/login/log_bg.png" mode="scaleToFill" class="bg"></image>
		 -->
		<view class="content" :style="{'background':kbackgroundColor}" style="min-height: 100vh">
			<!-- <image src="/static/login/login_bg.png" mode="scaleToFill" class="user_bg"></image> -->
			<view class="logo_box">
				<image v-if="ktheme == 'purple'" src="/static/login/logo.png" mode="scaleToFill"
					style="border-radius: 20rpx;" class="logo_box-img"></image>
				<image v-if="ktheme == 'black'" src="/static/login/logo-black.png" mode="scaleToFill"
					style="border-radius: 20rpx;" class="logo_box-img"></image>
			</view>
			<view class="titleWrap">
				<!-- <view class="color-o fsz64 logo_box-title">
				Hello！
			</view> -->
				<image v-if="ktheme == 'purple'" class="hello-img" src="/static/login/hello.png" mode="scaleToFill">
				</image>
				<image v-if="ktheme == 'black'" class="hello-img" src="/static/login/hello-black.png"
					mode="scaleToFill"></image>
				<view class="hello-title" :style="{'color':knormalColor}">欢迎来到金币世界 </view>
			</view>
			<view class="input_box">
				<view class="input_boxx">
					<!-- 	<view class="input_title">
					手机号
				</view> -->
					<view class="input_panel">
						<!-- <view class="input_left">
						+86
					</view> -->
						<input type="text" class="inputer" placeholder-class="inputer_placeholder" placeholder="请输入手机号码"
							v-model="mobile" :maxlength="maxMobile">
					</view>
				</view>
				<view class="input_boxx">
					<!-- 	<view class="input_title">
					密码
				</view> -->
					<view class="input_panel">
						<!-- <view class="input_left">
						密码
					</view> -->
						<input type="text" :password='show_pass' v-model="pwd" class="inputer" placeholder="请输入密码"
							placeholder-class="inputer_placeholder">
						<view class="" @click="change_show_pass()">
							<n-icon name="attentionforbidfill" size="30" v-if="show_pass" color="#7a7a7a"></n-icon>
							<n-icon name="attentionfill" size="30" v-else color="#7a7a7a"></n-icon>
						</view>

					</view>
				</view>
				<view class="nav_box">
					<view class="codeLogoin" :style="{color:selectColorSize}" @click="toCode">验证码登录</view>
					<view :style="{'color':knormalColor}" @click="goForgetpwd">忘记密码</view>
				</view>
				<view class="login_btn" style="margin-top: 30rpx;" :style="{background:kbuttonBgColor}"
					@click="loginHandler()">登录</view>
				<view :style="[{'background': (ktheme != 'purple' ? 'black':' #dcdcdc')},{'color':knormalColor}]"
						class="toReg"
						@click="toReg()">
					注册新用户
				</view>
				<view class="" style="min-height: 240rpx">
					<!-- #ifdef APP-PLUS || APP-PLUS-NVUE -->
					<view class="third-login">
						<view :style="{'color':knormalColor}" class="regBtn"
							style="display: flex;justify-content: space-between; align-items: center;">
							<view class="tbx"> </view> 其他登录方式 <view class="tbx2"> </view>
						</view>
						<image class="third-icon" src="/static/image/ic-wechat.png" mode="widthFix"
							@click="handleThirdLoginApp()"></image>
					</view>
					<!-- #endif -->
					<!-- #ifdef APP-PLUS || APP-PLUS-NVUE -->
					<!-- <view class="fz12 g5" v-if="thirdPartyLogins.length > 0">第三方账号登录：</view>
					<view class="flc third-block" v-if="thirdPartyLogins.length > 0">
						<view class="third-item" v-for="(item, key, index) in thirdPartyLogins" :key="key"
							@click="handleThirdLoginApp(item)" v-if="item == 'weixin'">
							<image class="third-item-img" src="/static/image/ic-wechat.png" mode="aspectFill"
								v-if="item == 'weixin'"></image>
						</view>
					</view> -->
					<!-- #endif -->
				</view>
				<view class="agree_box"  @tap="agree()">
					<radio :checked="is_agree" style="transform: scale(.6);" />
					<view :style="{'color':knormalColor}">我已同意金币世界<text :style="{color:selectColorSize}"
							@click="goAgreement()">《用户隐私协议》</text>
						及<text @click="goPrivacy()" :style="{color:selectColorSize}">《服务协议》</text></view>
				</view>
				<!-- 请阅读并同意用户隐私协议和服务协议! -->
				<uni-popup ref="confirmDialog" type="center" :maskBackgroundColor="'rgba(0,0,0,0.5)'"
					:isMaskClick="false">
					<view class="store-view store-border-all tips-padding"
						:style="{'background':kbackgroundColor,color:knormalColor}"
						:class="[{'alert-border-black alert-border-shadow-black':ktheme =='black'},{'alert-border-purple':ktheme =='purple'}]">
						<text class="popup-title">提示</text>
						<text class="popup-subtitle">请阅读并同意用户隐私协议和服务协议!</text>
						<view class="tips-bottom">
							<view class="tips-button"
								:class="[{'tips-cancel-bg-black':ktheme =='black'},{'tips-cancel-bg-white':ktheme =='purple'}]"
								@click="colfirmClose()">关闭</view>
							<view class="tips-button" :style="{background:kbuttonBgColor}" @click="confirmCheck()">确定勾选
							</view>
						</view>
					</view>
				</uni-popup>
				<!--未绑定  -->
				<uni-popup ref="bindingDialog" type="center" :maskBackgroundColor="'rgba(0,0,0,0.5)'"
					:isMaskClick="false">
					<view class="store-view store-border-all tips-padding"
						:style="{'background':kbackgroundColor,color:knormalColor}"
						:class="[{'alert-border-black alert-border-shadow-black':ktheme =='black'},{'alert-border-purple':ktheme =='purple'}]">
						<text class="popup-title">提示</text>
						<text class="popup-subtitle">未绑定,请登录后前往设置进行绑定!</text>
						<view class="tips-bottom">
							<view class="tips-button"
								:class="[{'tips-cancel-bg-black':ktheme =='black'},{'tips-cancel-bg-white':ktheme =='purple'}]"
								@click="bindingClose()">关闭</view>
							<view class="tips-button" :style="{background:kbuttonBgColor}" @click="bindingCheck()">确定
							</view>
						</view>
					</view>
				</uni-popup>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		baseUrl
	} from '@/config/config.js';
	import {
		goBack,
		jumpBackPage
	} from '@/config/mixins.js';
	export default {
		mixins: [goBack, jumpBackPage],
		data() {
			return {
				borderSty: this.$store.state.borderSty, //选中背景线颜色
				selectColorSize: this.$store.state.selectColorSize, //字体
				buttonBcak: this.$store.state.buttonBcak, //按钮颜色
				maxMobile: 11,
				mobile: '', // 手机号
				pwd: '', // 密码
				isCaptcha: false, // 是否需要验证码
				captcha: '', // 输入的验证码
				captchaUrl: '', // 验证码图片地址
				btnb: 'btn btn-square btn-c btn-all', // 按钮bg
				weixinBrowser: false, // 是否是微信浏览器
				thirdPartyLogins: [], // 第三方登录列表
				is_agree: false,
				show_pass: true,
			};
		},
		onLoad(options) {
			//#ifdef H5

			// window.location.href = 'https://shucang.zhongfujiayi.com/wap/#/pages/user/user'
			console.log("h5--:")

			// #endif
			//#ifdef APP-PLUS
			console.log("--app:", )
			//app

			//#endif
			if (options.invitecode) {
				this.$db.set('invitecode', options.invitecode);
			}
			// 判断浏览器环境
			this.weixinBrowser = this.$common.isWeiXinBrowser();

			if (this.weixinBrowser) {
				this.getAuths();
			}
			// #ifdef APP-PLUS || APP-PLUS-NVUE
			this.getAppAuths();
			// #endif
		},
		onShow() {
			if (this.$db.get('userToken')) {
				uni.switchTab({
					url: '/pages/index/index'
				});
			}
		},
		computed: {
			// 动态更改登录按钮bg
			loginButtonClass() {
				return this.mobile && this.mobile.length > 0 && this.pwd ? this.btnb + ' btn-b' : this.btnb;
			},
			logoImage() {
				return this.$store.state.config.shop_logo;
			},
			getThirdLoginImg(key) {
				return key => {
					if (key == 'Wxofficial') {
						return '/static/image/ic-wechat.png';
					} else if (key == 'weixin') {
						return '/static/image/ic-wechat.png';
					}
				};
			}
		},
		onPullDownRefresh() {
			setTimeout(function() {
				uni.stopPullDownRefresh()
			}, 1000)
		},
		methods: {
			bindingCheck() {
				this.$refs.bindingDialog.close()
			},
			bindingClose() {
				this.$refs.bindingDialog.close()
			},
			// 关闭
			colfirmClose() {
				this.$refs.confirmDialog.close()
			},
			// 确定勾选
			confirmCheck() {
				this.is_agree = true
				this.$refs.confirmDialog.close()

			},
			change_show_pass() {
				this.show_pass = !this.show_pass
			},
			agree: function() {
				this.is_agree = !this.is_agree
			},
			// 验证手机号
			rightMobile() {
				let res = {};
				if (!this.mobile) {
					res.status = false;
					res.msg = '请输入手机号';
				} else if (!this.validateMobile(this.mobile)) {
					res.status = false;
					res.msg = '手机号格式不正确';
				} else if (!this.pwd) {
					res.status = false;
					res.msg = '请输入密码';
				} else {
					res.status = true;
				}
				return res;
			},
			// 判断手机号码是否正确
			validateMobile(phone) {
				const re = /^1(3|4|5|7|8|9|6)\d{9}$/
				return re.test(phone);
			},
			// 登录处理
			loginHandler() {
				if (!this.is_agree) {
					this.$refs.confirmDialog.open()
					//	this.$common.errorToShow('请阅读并同意用户隐私协议和服务协议!')
					return;
				}
				if (!this.mobile) {
					this.$common.errorToShow('请输入手机号');
				} else if (!this.validateMobile(this.mobile)) {
					this.$common.errorToShow('手机号格式不正确');
				} else if (!this.pwd) {
					this.$common.errorToShow('请输入密码');
				} else {
					this.toLogin();
				}
				// if (this.mobile && this.mobile.length > 0 && this.pwd) {
				// 	if (!this.validateMobile(this.mobile)) {
				// 		this.$common.errorToShow('请填写正确的手机号码!')
				// 	    return false;
				// 	}
				// 	this.toLogin();
				// 	// if (!this.rightMobile().status) {
				// 	// 	this.$common.errorToShow(this.rightMobile().msg);
				// 	// } else {
				// 	// 	this.toLogin();
				// 	// }
				// }
			},
			// 获取验证码图片地址
			getCaptchaUrl() {
				this.captchaUrl = this.$config.apiBaseUrl + 'captcha.html';
			},
			getCodeImg() {
				let num = Math.ceil(Math.random() * 1000);
				this.captchaUrl = this.$config.apiBaseUrl + 'captcha.html?' + num;
			},
			// 去注册
			toReg() {
				this.$common.navigateTo('/pages/login/register?mobile=' + this.mobile);
			},
			// 登录
			toCode() {
				this.$common.navigateTo('/pages/login/loginByCode?mobile=' + this.mobile);
			},
			// 去登录
			toLogin() {
				let data = {
					account: this.mobile,
					password: this.pwd
				};

				if (this.isCaptcha) {
					data.captcha = this.captcha;
				}

				// 获取邀请码
				let invicode = this.$db.get('invitecode');
				if (invicode) {
					data.invitecode = invicode;
				}
				this.$api.login(data, res => {
					if (res.status) {
						this.$db.set('userToken', res.data.token);
						this.redirectHandler();
					} else {
						this.$common.errorToShow(res.message, () => {
							// 绑定手机号
							if (res.data === '11027') {
								this.$db.set('userToken', res.token);
								this.$common.navigateTo("/pages/login/mobile/index")
							}
							// 需要输入验证码 或者 验证码错误刷新
							if (res.data === 10013 || res.data === 10012) {
								this.isCaptcha = true;
							}

							// 登录需要验证码
							if (this.isCaptcha) {
								this.getCaptchaUrl();
							}

						});
					}
				});
			},
			redirectHandler() {
				this.$common.successToShow('登录成功!', () => {
					this.$db.del('invitecode');
					// this.handleBack();、
          let invite_way = uni.getStorageSync('invite_way')
          if (invite_way === 'ai') {
            uni.navigateTo({
              url: '/pages/aipicture/finish/ai_invite'
            })
          } else {
            uni.navigateTo({
              url: '/pages/aipicture/finish/normal_invite'
            })
          }
					// 	uni.switchTab({
					// 		url: '/pages/index/index'
					// 	})
				});
			},
			// 登录方式切换
			selectLoginType() {
				this.$common.redirectTo('/pages/login/loginByCode');
			},
			// 获取第三方登录列表
			getAuths() {
				let data = {
					url: baseUrl + 'wap/pages/author'
				};
				this.$api.getTrustLogin(data, res => {
					if (res.status) {
						this.thirdPartyLogins = res.data;
					}
				});
			},
			// 第三方登录授权
			handleThirdLogin(url) {
				this.$common.redirectTo('');
				let redirect = this.$store.state.redirectPage;
				// console.log("第三方登录vuex"+redirect);
				this.$db.set('redirectPage', redirect);
				// console.log("第三方登录本地存储"+this.$db.get('redirectPage'));
				window.location.href = url;
			},
			//获取APP信任登录
			getAppAuths() {
				let _this = this;
				_this.thirdPartyLogins = [];
				uni.getProvider({
					service: 'oauth',
					success: function(res) {
						if (res.errMsg == 'getProvider:ok') {
							_this.thirdPartyLogins = res.provider;
						}
					}
				});
			},

			handleThirdLoginApp() {
				var _this = this
				uni.login({
					"provider": "weixin",
					"onlyAuthorize": true, // 微信登录仅请求授权认证
					success: function(event) {
						const {
							code
						} = event
						var data = {
							code: code
						}
						//客户端成功获取授。权临时票据（code）,向业务服务器发起登录请求。
						_this.$api.appSigninWeixin(data, res => {
							if (res.status) {
								_this.$common.successToShow("登录成功");
								_this.$db.set('userToken', res.data.token);
								uni.switchTab({
									url: '/pages/index/index'
								})
							}
							if (res.code == 2002001) {
								uni.navigateTo({
									url: '/pages/login/bindingwx'
								})
							} else {
								_this.$common.errorToShow(res.message);
							}
						})

					},
					fail: function(err) {
						// 登录授权失败
						// err.code是错误码
					}
				})

				// var weixinOauth = null;
				// plus.oauth.getServices(function(services) {
				// 	for (var i in services) {
				// 		var service = services[i];
				// 		// 获取微信登录对象
				// 		if (service.id == 'weixin') {
				// 			weixinOauth = service;
				// 			break;
				// 		}
				// 	}
				// 	weixinOauth.login( function(oauth){
				// 			console.log("oauth",oauth);// 授权成功，weixinOauth.authResult 中保存授权信息
				// 			uni.login({
				// 				"provider": "weixin",
				// 				"onlyAuthorize": true, // 微信登录仅请求授权认证
				// 				success: function(event) {
				// 					const {code} = event
				// 					var data={code:code}
				// 						console.log("code--", code);
				// 					//客户端成功获取授。权临时票据（code）,向业务服务器发起登录请求。
				// 					_this.$api.appSigninWeixin(data,res=>{
				// 						console.log("res----登录",res);
				// 					})
				// 				},
				// 				fail: function(err) {
				// 					// 登录授权失败
				// 					// err.code是错误码
				// 				}
				// 			})

				// 	}, function(err) {
				// 		console.log("err--1",err);
				//     // 登录授权失败
				//     // err.code是错误码
				// 	})
				// }, function(err) {
				// 		console.log("err--2",err);
				// 	// 获取 services 失败
				// })
			},
			//app第三方登录
			handleThirdLoginApp2() {
				let type = 'weixin'
				// this.$common.errorToShow('功能暂未开放')
				// return
				uni.showLoading({
					title: '加载中'
				});
				let _this = this;
				uni.login({
					provider: type,
					// "onlyAuthorize": true, // 微信登录仅请求授权认证
					success: function(loginRes) {
						// 获取用户信息
						uni.getUserInfo({
							provider: type,
							success: function(infoRes) {
								if (infoRes.errMsg == 'getUserInfo:ok') {
									var data = {
										user: infoRes.userInfo,
										type: type
									};
									var invitecode = _this.$db.get('invitecode');
									if (invitecode) {
										data.invitecode = invitecode;
									}
									_this.$api.appTrustLogin(data, res => {
										uni.hideLoading();
										if (res.status) {
											//判断是否返回了token，如果没有，就说明没有绑定账号，跳转到绑定页面
											if (typeof res.data.token == 'undefined') {
												uni.redirectTo({
													url: '/pages/login/login/index?user_wx_id=' +
														res.data.user_wx_id
												});
											} else {
												//登陆成功，设置token，并返回上一页
												_this.$db.set('userToken', res.data.token);
												uni.navigateBack({
													delta: 1
												});
												return false;
											}
										} else {
											_this.$common.errorToShow('登录失败，请重试');
										}
									});
								} else {
									uni.hideLoading();
									_this.$common.errorToShow('登录失败，请重试');
								}
							}
						});
					},
					fail() {
						uni.showModal({
							content: '未取得APPID',
							success: function(res) {
								if (res.confirm) {


								}
							}
						});
					},
					complete() {
						uni.hideLoading()
					}
				});
			},
			// 跳转到用户协议
			goAgreement() {
			//	window.location.href = "/static/html/service-agreement.html"
				// #ifdef H5
				console.log("---");
				window.location.href = "/static/html/service-agreement.html"
				// #endif
				// #ifdef APP-PLUS
				console.log("--1-");
				uni.navigateTo({
					url: '/pages/user/webview/webview?url=/static/html/service-agreement.html'
				})
				// #endif
				// let articleId = this.$store.state.config.user_agreement_id;
				// this.$common.navigateTo('/pages/article/index?id_type=1&id=' + 1);
			},
			// 跳转到隐私政策
			goPrivacy() {
				// #ifdef H5
			 	window.location.href = "/static/html/privacy-agreement.html"
				// #endif
				// #ifdef APP-PLUS
				uni.navigateTo({
					url: '/pages/user/webview/webview?url=/static/html/privacy-agreement.html'
				})
				// #endif

				// let articleId = this.$store.state.config.privacy_policy_id;
				//	 this.$common.navigateTo('/pages/article/index?id_type=1&id=' + 2);
			},
			goForgetpwd() {
				this.$common.navigateTo('/pages/login/password');
			}
		}
	};
</script>

<!--suppress CssInvalidPropertyValue -->
<style>
	@import '/pages/login/login.css';
</style>
